<?php

/* * ****************************************
 * 从阿里妈妈获取商品
 *
 * '数码相机/摄像机/摄影器材' => array( 'cid' => '14', 'pageno' => '3' ),
 *  cid表示淘宝分类的id, pageno表示获取多少页数据
 *  不重要的分类可以注释掉不去获取（重点获取衣服，数码类商品）
 * *************************************** */

require_once ( 'config.inc.php' );

$logger = GetAuditLogger("getproduct_audit.log");
$DBInstance = new DB();

//商品1级分类列表数组（根据商品的1级分类获取商品）

/* 	$cateArry = $DBInstance->GetPlan("select cate_name, taobao_cid from product_category");
  foreach($cateArry as $k=>$v){

  echo "'".$v['cate_name']."'  =>  array( 'cid' => '".$v['taobao_cid']."', 'pageno' => '3' ),";
  echo "<br>";
  }
 */
//第一步：
//根据商品分类里的商品写入数据库
$Taoapi = new Taoapi;

//读取每个category
foreach ($cateList as $k => $v) {

    //读取每个category里的分页
    for ($pn = $v['pageno']; $pn > 0; $pn--) {

        $Taoapi->method = 'taobao.taobaoke.items.get';
        $Taoapi->fields = 'num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,item_location,volume';
        $Taoapi->nick = TAOBAOKE_ID;
        $Taoapi->cid = $v['cid'];
        $Taoapi->start_credit = '3diamond'; //3钻以上
        $Taoapi->end_credit = '5goldencrown'; //5皇冠一下
        $Taoapi->sort = 'commissionNum_desc'; //按照成交量

        $Taoapi->page_no = $pn;
        $Taoapi->page_size = 40; //每页40个商品
        $TaobaoData = $Taoapi->Send('get', 'xml')->getArrayData();

        if ($Taoapi->getErrorInfo()) {
            echo "API获取数据遇到错误,错误提示是:";
            print_r($Taoapi->getErrorInfo());
            die();
        }

//			print_r($TaobaoData);
        $tbData = $TaobaoData['taobaoke_items']['taobaoke_item'];

        //读取每个分页里的40个商品
        foreach ($tbData as $tbkey => $tbvalue) {

            $num_iid = $tbvalue['num_iid'];

            //如果商品之前已经存在，就不再入库
            $isexist = $DBInstance->GetValue("select taobao_id from product_info_taobao where taobao_id = $num_iid");

            if (!$isexist) {

                $shopNick = edp_db_input($tbvalue['nick']);
                $productName = edp_db_input($tbvalue['title']);
                $productPicture = edp_db_input($tbvalue['pic_url']);
                $productPrice = $tbvalue['price'];
                $productCategory = ConvertTaobaoProductCid($v['cid']);
                $productLocation = GetCityID($tbvalue['item_location']);
                $clickURL = edp_db_input($tbvalue['click_url']);
                $commission_rate = $tbvalue['commission_rate'];
                $volume = intval($tbvalue['volume']);

                $productDetailURL = 'http://item.taobao.com/item.htm?id=' . $tbvalue['num_iid'];

                try {
                    $DBInstance->BeginTransaction();
                    $now = GetCurrentDate();

                    //这里临时在product_info里加入了nick字段	作为第二步使用
                    $sql = "insert into product_info( cate_id, shop_id, product_name, product_url, pic_path,
                                location, price, description,
                                status, create_user_id, create_time, nick, volume )
                            values( $productCategory, '', '$productName',
                                '$productDetailURL', '$productPicture',
                                '$productLocation', '$productPrice', '',
                                1, 1, '$now', '$shopNick', $volume ) ";

                    $DBInstance->Insert($sql);
                    $id = $DBInstance->LastID();

                    $sql = " insert into product_info_taobao values( $id, '$num_iid', '$clickURL', '$commission_rate' ) ";
                    $DBInstance->Insert($sql);

                    $logger->error("product " . $num_iid . " successfully added");
                } catch (Exception $e) {
                    $DBInstance->Rollback();
                    return false;
                }
                $DBInstance->Commit();
            }
        }
    }
}

$logger->error("product insert finished");

//第二步：
//更新新插入数据库的商品的shop_id字段，将product_info与shop_info绑定
//这里只更新了shop已经存在的商品(可以改造一下：将不存在的shop先insert shop_info，再和商品绑定，这里没做)
$productList = $DBInstance->GetPlan('select p.id, p.nick, pt.taobao_id from product_info p, product_info_taobao pt where p.shop_id=0 and p.id=pt.product_id');
$Taoapi = new Taoapi;

foreach ($productList as $pkey => $pvalue) {

    //为了提高查询速度，最好给nick创建下索引create index shop_info_nick on shop_info(nick);
    $sid = $DBInstance->GetValue("select id from shop_info where nick ='" . $pvalue['nick'] . "'");
    //如果该商品的shop_id存在
    if ($sid) {
        $sql = "update product_info set shop_id=" . $sid . "  where id=" . $pvalue['id'];
        $DBInstance->Update($sql);
    } else {
        // if shop does not exist, add it
        $Taoapi->method = 'taobao.shop.get';
        $Taoapi->fields = 'sid,cid,nick,title,desc,bulletin,pic_path,created,modified';
        $Taoapi->nick = $pvalue['nick'];
        $TaobaoData = $Taoapi->Send('get', 'xml')->getArrayData();

        if (edp_is_empty_string($Taoapi->getErrorInfo())) {

            $extShopID = $TaobaoData['shop']['sid']; //taobao平台的扩展id，作为shop_info_taobao的主键
            $shopName = $TaobaoData['shop']['title'];
            $createdDate = substr($TaobaoData['shop']['created'], 0, 10);
            $shopDesc = $TaobaoData['shop']['desc'];
            $logoURL = TAOBAO_PIC_PREFIX.$TaobaoData['shop']['pic_path'];
            if( is_array( $logoURL ) ){
                $logURL = "";
            }
            $shopURL = "http://shop$extShopID.taobao.com";
            $nickName = $pvalue['nick'];
            if (is_array($TaobaoData['shop']['desc'])) {
                $shopDesc = $TaobaoData['shop']['desc'][0];
            } else {
                $shopDesc = $TaobaoData['shop']['desc'];
            }

            //get Shop category
            $result=$DBInstance->GetRow("select id, parent_id from shop_category where taobao_cid=".$TaobaoData['shop']['cid']);
			if($result){
			   $shopCategory = $result['id'];
			}else
			   $shopCategory = 0;//找不到返回0

            // add taobaoke information to shop
            $Taoapi->method = 'taobao.taobaoke.shops.convert';
            $Taoapi->fields = 'user_id,shop_title,click_url,shop_commission.rate';
            $Taoapi->sids = $extShopID;
            $Taoapi->nick = TAOBAOKE_ID;
            $TaobaokeData = $Taoapi->Send('get', 'xml')->getArrayData();

            if (edp_is_empty_string($Taoapi->getErrorInfo()) && !empty($TaobaokeData)) { //如果存在click_url,commissionURL肯定是自己的推广链接
                $commissionURL = $TaobaokeData['taobaoke_shops']['taobaoke_shop']['click_url'];
                $commissionRate = $TaobaokeData['taobaoke_shops']['taobaoke_shop']['shop_commission.rate'];
                if( $commissionRate == "" ){
                    $commissionRate = 0;
                }
                $status = ADDSHOP_STATUS_SUCCESS;
            } else {
                $commissionRate = '0';
                $commissionURL = $shopURL;
                $status = ADDSHOP_STATUS_MISS_TAOBAOAPI_DATA;
            }

            $sql = "insert into
				shop_info( plat_id, shop_name, shop_url, logo_url, nick, created, location, description,
								 status, create_user_id, create_time, cate_id_list)
				values( 1, '$shopName', '$shopURL', '$logoURL', '$nickName', '$createdDate', '0', '$shopDesc',
						$status, 1, NOW(), '$shopCategory' ) ";

            $DBInstance->Insert( $sql );
            $shop_id = $DBInstance->LastID();

            $sql = " insert into shop_info_taobao values( $shop_id, '$extShopID', '$commissionURL', '$commissionRate', 0 ) ";
			$DBInstance->Insert( $sql );

            // at last update product information
            $sql = "update product_info set shop_id=" . $shop_id . "  where id=" . $pvalue['id'];
            $DBInstance->Update($sql);

            $logger->error( "product ".$pvalue['id']." successfully updated with newly added shop:". $shop_id );
        } else {
            $logger->error("Cannot find corresponding shop for: ". $pvalue['nick']);
        }
    }
}

$logger->error("update product shop_info finished");

//第三步：
//执行sql语句，删除product_info里shop_id没有更新的商品
//执行sql语句，删除product_info的nick字段
function ConvertTaobaoProductCid($taobao_cid) {

    global $DBInstance;
    $result = $DBInstance->GetRow("select id, parent_id from product_category where taobao_cid=" . $taobao_cid);

    if ($result) {

        if ($result['parent_id'] == '0') {
            return $result['id'];
        }
        while ($result['parent_id'] != '0') {
            $result = $DBInstance->GetRow("select id, parent_id from product_category where id=" . $result['parent_id']);
        }
        return $result['id'];
    }else
        return '0'; //找不到返回0
}

?>
